const koa = require("koa")
const koaBody = require("koa-body")
const static = require("koa-static")
const router = require("koa-router")()
const fs = require("fs")
const path = require("path")
const main = require("./model")
const render = require("koa-art-template")
const {ObjectId} = require("mongodb")
const app = new koa()
router.get("/movies",async ctx=>{
    await ctx.render("movies")
})
router.get("/chum",async ctx=>{
    await ctx.render("chum")
})
router.get("/find",async ctx=>{
    var table = await main("user")
    var result = await table.find().toArray()
    await ctx.render("home",{result})
})
router.get("/detail",async ctx=>{
    var {_id} = ctx.query
    var table = await main("user")
    var result = await table.find({_id:ObjectId(_id)}).toArray()
    ctx.body = result
})
router.post("/doForm",async ctx=>{
    var {name,age,sex} = ctx.request.body
    age = Number(age)
    var fileName = ctx.request.files.logo.path
    var reader = fs.createReadStream(fileName)
    var uploadFile = `./static/${path.basename(fileName)}`
    var writer = fs.createWriteStream(uploadFile)
    reader.pipe(writer)
    var logo = ctx.origin+"/"+path.basename(fileName)
    var table = await main("user")
    await table.insertOne({name,age,sex,logo})
    await ctx.redirect("/movies")
})
router.post("/doChum",async ctx=>{
    var {name,age,sex,like} = ctx.request.body
    var logo = ctx.request.files.logo.path
    var reader = fs.createReadStream(logo)
    var uploadFile = `./static/${path.basename(logo)}`
    var writer = fs.createWriteStream(uploadFile)
    reader.pipe(writer)
    var table = await main("chum")
    var pic = ctx.origin+"/"+path.basename(logo)
    await table.insertOne({name,age,sex,like,pic})
})
router.get("/detail/:id",async ctx=>{
    var {id} = ctx.params
    var table = await main("chum")
    var result = await table.find({_id:ObjectId(id)}).toArray()
    ctx.body = {
        code:200,
        data:result
    }
})
router.get("/overview",async ctx=>{
    ctx.set("Access-Control-Allow-Origin","*")
    var table = await main("chum")
    var res = await table.find().toArray()
    var total = await table.find().count()
    ctx.body = {
        code:200,
        res,
        total
    }
})
app.use(koaBody({
    multipart: true,
    formidable: {
        maxFileSize: 200 * 1024 * 1024,    
		keepExtensions: true
    }
}))
render(app,{
    root: path.join(process.cwd(), 'pages'),
    extname: '.html',
    debug: process.env.NODE_ENV !== 'production'
})
app.use(static(path.join(__dirname,"static")))
app.use(router.routes())
app.listen(8080)